package gopay

import (
	"context"
	"fmt"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"
	"github.com/spf13/viper"
)

// appid：应用ID
// privateKey：应用私钥，支持PKCS1和PKCS8

type PayData struct {
	OutTradeNo  string `json:"outTradeNo"`
	TotalAmount string `json:"totalAmount"`
	Subject     string `json:"subject"`
	ReturnUrl   string `json:"returnUrl"`
	NotifyUrl   string `json:"notifyUrl"`
}

// 初始化支付宝客户端
func NewPayData() *PayData {
	return &PayData{}
}
func (p *PayData) Pay(s *PayData) (string, error) {
	client, err := alipay.NewClient(viper.GetString("alipay_app_id"), viper.GetString("private_key"), false)
	if err != nil {
		return "", fmt.Errorf("支付宝错误信息:::%v", err)
	}
	client.DebugSwitch = gopay.DebugOn // 打开Debug开关，输出日志，默认关闭
	err = client.SetCertSnByContent(
		[]byte(viper.GetString("app_public_cert")),
		[]byte(viper.GetString("alipay_root_cert")),
		[]byte(viper.GetString("alipay_public_cert")),
	)
	if err != nil {
		return "", fmt.Errorf("支付宝证书错误信息:::%v", err)
	}
	bm := make(gopay.BodyMap) // 初始化 BodyMap
	bm.Set("out_trade_no", s.OutTradeNo).
		Set("total_amount", s.TotalAmount).
		Set("subject", s.Subject).
		Set("product_code", "FAST_INSTANT_TRADE_PAY").
		Set("return_url", s.ReturnUrl).
		Set("notify_url", s.NotifyUrl)
	return client.TradePagePay(context.Background(), bm)
}
